let express = require('express');
let router = express.Router();
let filter = require('../../components/filter');
let qr_image = require('qr-image');

/**
 * 查询考试数据 by p 2018-06-13
 *
 * 按条件查询考试数据
 *
 */
router.get('/', filter.authorize, function (req, res, next) {
    let params = req.query;

    var limits = "";
    var sql = "";
    var datas = [];
    var user = req.session.user;

    if (user.roleId !== 1) {
        sql = "userId = ?";
        datas.push(user.id);
    }

    req.app.db.query("select count(1) as totalCount from exam " + (sql === "" ? "" : " where ") + sql + " order by id desc", datas, function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results[0].totalCount === 0) {
            res.json({"success": true, "data": {}, "totalCount": 0});
            return;
        }

        let totalCount = results[0].totalCount;

        if (params.pageNo > 0 && params.pageSize > 0) {
            limits = " limit ?, ?";
            datas.push((params.pageNo - 1) * params.pageSize);
            datas.push(params.pageSize * 1);
        }

        req.app.db.query("select * from exam " + (sql === "" ? "" : " where ") + sql + " order by id desc" + limits, datas, function (err, results, fields) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            res.json({"success": true, "data": results, "totalCount": totalCount});
        });
    });
});

/**
 * 查看考试数据 by p 2018-06-13
 *
 * 按id查看指定的考试信息
 */
router.get('/:id', filter.authorize, function (req, res, next) {
    let params = req.params;

    var datas = [];
    var user = req.session.user;

    var sql = "where id = ?";
    datas.push(params.id);

    if (user.roleId !== 1) {
        sql += " and userId = ?";
        datas.push(user.id);
    }

    req.app.db.query("select * from exam " + sql + " order by id desc", datas, function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": "当前用户无法查看此条考试信息！"});
            return;
        }

        res.json({"success": true, "data": results[0]});
    });
});


router.get('/:id/qrcode', filter.authorize, function (req, res, next) {
    let params = req.params;
    let url = "http://" + global["ip"] + (global["port"] === 80 ? "" : ":" + global["port"]) + global.contextPath + "/slogin.html?id=" + req.params.id + "&password=" + req.query.password;
    var temp_qrcode = qr_image.image(url);
    res.type('png');
    temp_qrcode.pipe(res);
});
/**
 * 修改考试信息 by v 2018-06-29
 *
 * 只能修改标题、开始结束时间、考试时间、房间密码，其他信息设计到试卷生产不让修改
 */
router.put('/:id', filter.authorize, function (req, res, next) {
    let params = req.body;

    if (!params.id > 0) {
        res.json({"success": false, "message": "考试编码错误！"});
        return;
    }

    if (params.title === undefined || params.title === "") {
        res.json({"success": false, "message": "考试名称不能为空！"});
        return;
    }

    if (params.beginTime === undefined || params.beginTime === "") {
        res.json({"success": false, "message": "请设置考试开始时间！"});
        return;
    }

    if (params.endTime === undefined || params.endTime === "") {
        res.json({"success": false, "message": "请设置考试结束时间！"});
        return;
    }

    if (params.totalTimes === undefined || params.totalTimes === "") {
        res.json({"success": false, "message": "请设置考试时间（分钟）！"});
        return;
    }

    if (params.password === undefined || params.password === "") {
        res.json({"success": false, "message": "请设置考场密码！"});
        return;
    }

    req.app.db.query('update exam set title = ?, beginTime = ?, endTime = ?, totalTimes = ?, password = ? where id = ?', [params.title, params.beginTime, params.endTime, params.totalTimes, params.password, params.id], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        res.json({"success": true, "message": global.putMsg});
    });
});

router.put('/:id/actived', filter.authorize, function (req, res, next) {
    let params = req.body;

    if (!params.id > 0) {
        res.json({"success": false, "message": "考试编码错误！"});
        return;
    }

    req.app.db.query('update exam set isActived = 1 where id = ?', [params.id], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        res.json({"success": true, "message": "考试已开启！！！"});
    });
});

router.put('/:id/deactived', filter.authorize, function (req, res, next) {
    let params = req.body;

    if (!params.id > 0) {
        res.json({"success": false, "message": "考试编码错误！"});
        return;
    }

    req.app.db.query('update exam set isActived = 0 where id = ?', [params.id], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        res.json({"success": true, "message": "考试已关闭！！！"});
    });
});

/**
 * 新增考试数据 by p 2018-06-13
 *
 *
 */
router.post('/', filter.authorize, function (req, res, next) {
    let params = req.body;
    let user = req.session.user;

    var id = 0;
    var singleNum = 0;
    var singleScore = 0;
    var multiNum = 0;
    var multiScore = 0;
    var num = 1;

    if (params.subjectIds === undefined || params.subjectIds === "") {
        res.json({"success": false, "message": "父类编码不正确！"});
        return;
    }

    if (params.title === undefined || params.title === "") {
        res.json({"success": false, "message": "考试名称不能为空！"});
        return;
    }

    if (params.singleNum !== undefined && params.singleNum !== "" && params.singleNum > 0) {
        singleNum = params.singleNum;
    }

    if (params.singleScore !== undefined && params.singleScore !== "" && params.singleScore > 0) {
        singleScore = params.singleScore;
    }

    if (params.multiNum !== undefined && params.multiNum !== "" && params.multiNum > 0) {
        multiNum = params.multiNum;
    }

    if (params.multiScore !== undefined && params.multiScore !== "" && params.multiScore > 0) {
        multiScore = params.multiScore;
    }

    if (singleNum > 0 && singleScore === 0) {
        res.json({"success": false, "message": "请设置单选题分数！"});
        return;
    }

    if (multiNum > 0 && multiScore === 0) {
        res.json({"success": false, "message": "请设置多选题分数！"});
        return;
    }

    if (singleNum === 0 && multiNum === 0) {
        res.json({"success": false, "message": "请设置单选题或多选题数量！"});
        return;
    }

    // if (params.beginTime === undefined || params.beginTime === "") {
    //     res.json({"success": false, "message": "请设置考试开始时间！"});
    //     return;
    // }
    //
    // if (params.endTime === undefined || params.endTime === "") {
    //     res.json({"success": false, "message": "请设置考试结束时间！"});
    //     return;
    // }

    if (params.totalTimes === undefined || params.totalTimes === "") {
        res.json({"success": false, "message": "请设置考试时间（分钟）！"});
        return;
    }

    if (params.num !== undefined && params.num !== "" && params.num > 0) {
        num = params.num;
    }

    if (params.password === undefined || params.password === "") {
        res.json({"success": false, "message": "请设置考场密码！"});
        return;
    }

    req.app.db.query("call pro_exam_add(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", [id, params.subjectIds, params.title, singleNum, singleScore, multiNum, multiScore, params.beginTime, params.endTime, params.totalTimes, num, params.password, user.id], function (err, results) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length > 0) {
            if (results[0].length > 0) {
                if (results[0][0].id > 0) {
                    res.json({"success": true, "message": global.postMsg});
                    return;
                }
            }
        }

        res.json({"success": false, "message": "创建考试错误！", "detail": results});
    });
});

/**
 * 删除考试信息 by v 2018-06-13
 *
 * 按id删除指定的考试信息
 */
router.delete('/:id', function (req, res, next) {
    let params = req.params;
    let user = req.session.user;

    // 查询考试
    req.app.db.query("select * from exam where id = ?", [params.id], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": "考试信息错误！"});
            return;
        }

        if (user.id !== 1 && results[0].userId !== user.id) {
            res.json({"success": false, "message": "非录入用户不能删除考试信息！"});
            return;
        }

        // 删除考试
        req.app.db.query('delete from exam where id = ?', [params.id], function (err, results, fields) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            res.json({"success": true, "message": global.deleteMsg});
        });
    });
});

module.exports = router;
